package io.renren.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.constant.WeChatConstants;
import io.renren.common.exception.RenException;
import io.renren.common.utils.HttpUtils;
import io.renren.common.utils.RestTemplateUtil;
import io.renren.dto.WeChatAccessPhoneNumberVo;
import io.renren.dto.WeChatAccessTokenVo;
import io.renren.dto.WeChatMiniAuthorizeVo;
import io.renren.service.WechatNewService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WechatNewServiceImpl implements WechatNewService {

    private static final Logger logger = LoggerFactory.getLogger(WechatNewServiceImpl.class);
    @Value("${wx.wechat_appid}")
    private String appId;
    @Value("${wx.wechat_appsecret}")
    private String secret;

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    /**
     * 获取小程序accessToken
     *
     * @return accessToken
     */
    @Override
    public String getMiniAccessToken() {
        WeChatAccessTokenVo accessTokenVo = getAccessToken(appId, secret, "mini");
        return accessTokenVo.getAccessToken();
    }


    @Override
    public WeChatAccessPhoneNumberVo miniPhoneCode(String code) {
        String accessToken = getMiniAccessToken();
        String url = StrUtil.format(WeChatConstants.WECHAT_MINI_GET_PHONE_URL, accessToken);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", code);
        JSONObject jsonData = JSONObject.parseObject(JSONObject.toJSONString(map));
        String result = restTemplateUtil.postJsonData(url, jsonData);
        JSONObject data = JSONObject.parseObject(result);
        if (ObjectUtil.isNull(data)) {
            throw new RenException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !"0".equals(data.getString("errcode"))) {
            if (data.containsKey("errmsg")) {
                throw new RenException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
        return JSONObject.parseObject(data.toJSONString(), WeChatAccessPhoneNumberVo.class);
    }


    /**
     * 获取微信accessToken
     *
     * @param appId  appId
     * @param secret secret
     * @param type   mini-小程序，public-公众号，app-app
     * @return WeChatAccessTokenVo
     */
    private WeChatAccessTokenVo getAccessToken(String appId, String secret, String type) {
        String url = StrUtil.format(WeChatConstants.WECHAT_ACCESS_TOKEN_URL, appId, secret);
        JSONObject data = restTemplateUtil.getData(url);
        if (ObjectUtil.isNull(data)) {
            throw new RenException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !"0".equals(data.getString("errcode"))) {
            if (data.containsKey("errmsg")) {
                // 保存到微信异常表
                throw new RenException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
        return JSONObject.parseObject(data.toJSONString(), WeChatAccessTokenVo.class);
    }


    /**
     * 小程序登录凭证校验
     *
     * @return 小程序登录校验对象
     */
    @Override
    public WeChatMiniAuthorizeVo miniAuthCode(String code) {
        String url = StrUtil.format(WeChatConstants.WECHAT_MINI_SNS_AUTH_CODE2SESSION_URL, appId, secret, code);
        String res = HttpUtils.get(url);
        JSONObject data = JSONObject.parseObject(res);
        if (ObjectUtil.isNull(data)) {
            throw new RenException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !"0".equals(data.getString("errcode"))) {
            if (data.containsKey("errmsg")) {
                // 保存到微信异常表
                throw new RenException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
        return JSONObject.parseObject(data.toJSONString(), WeChatMiniAuthorizeVo.class);
    }

}
